//继承模板
{extend name="public/base"}


//CSS
{block name="style"}
<link rel="stylesheet" href="__ADMIN_STATIC__/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" type="text/css">
{/block}



//正文区域
{block name="body"}{//---------------------------------------------------------------------------}
<div class="panel-wrap page-zzjg">
	<div class="panel-left">
    	<div class="panel-title cl">
        	<div class="l">
        	<button class="btn radius Hui-iconfont Hui-iconfont-fenlei" type="button" onclick="expandAll(this)"> 展开</button> 
        	</div>
            <div class="r">
            	<button class="btn btn-primary radius" type="button"  onclick="setFormAdd()"><i class="Hui-iconfont">&#xe600; </i>添加</button>
                <button class="btn btn-danger  radius" type="button" onclick="btn_delNode();"><i class="Hui-iconfont">&#xe6e2; </i>删除</button>
                <button class="btn btn-success  radius" type="button" title="刷新" onclick="btn_zTree_reload();"><i class="Hui-iconfont">&#xe68f; </i>刷新</button>
            </div>	
        </div>
        <div class="tree">
            	<ul id="treeDemo" class="ztree"></ul>
        </div>
    	
    </div>
    <div class="panel-right">

    	<div class="page-container">
            
            <form action="{:url('save')}" method="post" class="form form-horizontal" id="form1" onsubmit="return false;">
			
				
            
            <fieldset class="pb-30">
            	<legend>组织结构-<span id="action_title">添加/修改</span></legend>
            	<div class="row cl">
                    <label class="form-label col-xs-4 col-sm-3">
                        <span class="c-red">*</span>名称：
                    </label>
                    <div class="formControls col-xs-6 col-sm-6">
                        <input type="text"  class="input-text" value="" placeholder="" name="name"
                        data-rule-required="true"/>

                        <input type="hidden" name="id" value=""/>
                    </div>
                </div>
                <div class="row cl">
                    <label class="form-label col-xs-4 col-sm-3">
                        <span class="c-red">*</span>上级：
                    </label>
                    <div class="formControls col-xs-6 col-sm-6">
                        <input type="text" readonly class="input-text" value="" placeholder="" name="pname" data-msg-required="请选择所在部门"  } 
							selectordeptname
                        />
                        <input type="hidden" name="pid" value=""   selectordeptid />
                    </div>
                </div>
                <div class="row cl">
                    <label class="form-label col-xs-4 col-sm-3">备注：</label>
                    <div class="formControls col-xs-6 col-sm-6">
                        <textarea name="info" cols="" rows="" class="textarea"  placeholder="说点什么...最少输入10个" inputLength="20"></textarea>

                        
                    </div>
                </div>

                <div class="row cl">
                    <label class="form-label col-xs-4 col-sm-3">部门位置</label>
                    <div class="formControls col-xs-6 col-sm-6">
                        <span class="select-box inline" >
							<select class="select" size="1" name="sort" >
								<option value="0" >同级部门最后位置</option>
                                <!-- <option value="1" >位于[XXXX]之前</option> -->
							</select>
						</span>
                            
                    </div>
                </div>

                <div class="row cl" style="margin-bottom:50px;">
                    <label class="form-label col-xs-4 col-sm-3"></label>
                    <div class="formControls col-xs-6 col-sm-6">

                        <button class="btn btn-primary radius" type="submit"><i class="Hui-iconfont">&#xe632; </i>  保存</button>
                            
                    </div>
                </div>
                
            </fieldset>
           
            </form>
        </div>
    </div>
</div>
{/block}
//-----------------------------------------------------------------------------------------------


<!--请在下方写此页面业务相关的脚本-->
//-----------------------------------------------------------------------------------------------
{block name="script"}
<script type="text/javascript" src="__ADMIN_STATIC__/lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script> 
<script type="text/javascript" __src="__ADMIN_STATIC__/lib/zTree/v3/js/jquery.ztree.exlog-0.1.js"></script> 
<script type="text/javascript">

;(function($){
	//alert('666');
})(jQuery);

var zTree , zNodes = [];
var t = $("#treeDemo");
var setting = {
	__edit: {
		drag: {
			autoExpandTrigger: true,
			// prev: dropPrev,
			// inner: dropInner,
			// next: dropNext
		},
		enable: true,
		showRemoveBtn: false,
		showRenameBtn: false
	},


	view: {
		dblClickExpand: false,  //双击展开
		showLine: true,        //是否显示 连接线
		selectedMulti: false,   //设置是否允许同时选中多个节点。默认值: true
		//showIcon:true , //是否显示图标
	},
	data: {
		key:{
			name: "name",
		},
		simpleData: {
			enable:true, 
			idKey: "id",
			pIdKey: "pid",
			rootPId: ""
		},
		

	},
	callback: {
		beforeClick:beforeClick, 
		onClick:onClick,
		// onRightClick: onRightClick,  
        onExpand: onExpand,  // 展开
        onCollapse: onCollapse,  // 折叠  
        // beforeDrag: beforeDrag,  
        // beforeDrop: beforeDrop,  
        // beforeDragOpen: beforeDragOpen  

	}
};






		// 展开
        function onExpand(event, treeId, treeNode){  
            var cookie = $.cookie("z_tree");  
              
            var z_tree = null;  
            if(cookie){  
                z_tree = JSON.parse(cookie);  
            }  
              
            if(!z_tree){  
                z_tree = new Array();  
            }  
            if(jQuery.inArray(treeNode.id, z_tree)<0){  
                z_tree.push(treeNode.id); //追加 
            }  
              
              
            $.cookie("z_tree", JSON.stringify(z_tree))  
        }  
        // 折叠  
        function onCollapse(event, treeId, treeNode){  
            var cookie = $.cookie("z_tree");  
              
            var z_tree = null;  
            if(cookie){  
                z_tree = JSON.parse(cookie);  
            }  
              
            if(!z_tree){  
                z_tree = new Array();  
            }  
            var index = jQuery.inArray(treeNode.id, z_tree);  
              
            z_tree.splice(index, 1); //删除  
              
            $.cookie("z_tree", JSON.stringify(z_tree))  
        }


        function beforeClick(treeId, treeNode, clickFlag) {
			console.log('beforeClick:' ,treeId, treeNode , clickFlag);

			//console.log( treeNode.id );

			loadData(treeNode.id);

			/*var zTree = $.fn.zTree.getZTreeObj("tree");
			if (treeNode.isParent) {
				//zTree.expandNode(treeNode);
				return false;
			} else {
				console.log(treeNode.file);
				demoIframe.attr("src",treeNode.file + ".html");
				return true;
			}*/
			//return (treeNode.click != false);
			
		}

		function onClick(event, treeId, treeNode, clickFlag){
		
		}

		//ajax 读取数据
		function loadData( id = null ){
			console.log('load:' , id );

			id = parseInt( id );


			var url = "{:url('get')}";
			var data = {};
				data.id = id;

			$.ajax({
	            type: "POST",
	            url: url,
	            data: data,
	            dataType: "json",
	            success: function(d){
	                    
	                    console.log('ajax_d : ' , d );
	                    if( !d ){
	                    	alert('没有找到！');
	                    }else{
	                    	//设置表单 修改
	                    	setFormUpdate(d);
	                    }
	            },
	            error:function( XMLHttpRequest, textStatus, errorThrown ){
	            	alert('ajax error : ' + textStatus );
	            }
			});
		}


		//设置表单 reset
		function setFormReset(){
			console.log('setFormReset:'  );

			var id = -999;
			var pid = -999;
			var $form = $('#form1');


			
			$form.find('#action_title ').text('添加') ; 
			

			$form.find('[name=name]').val('') ;  
			$form.find('[name=id]').val('') ;  

			$form.find('[name=pname]').val('') ;  
			$form.find('[name=pid]').val('') ;  

			$form.find('[name=info]').val('') ; 

			setSortSelect( id , pid ) ;  //获取排序select 下来菜单 $id = -999 , $pid = -999


		}

		//设置表单 修改
		function setFormUpdate( d ){
			console.log('setForm:' , d );


			var $form = $('#form1');


			
			$form.find('#action_title ').text('修改') ; 
			

			$form.find('[name=name]').val(d.name) ;  
			$form.find('[name=id]').val(d.id) ;  

			$form.find('[name=pname]').val(d.pname) ;  
			$form.find('[name=pid]').val(d.pid) ;  

			$form.find('[name=info]').val(d.info) ; 

			setSortSelect( d.id , d.pid ) ;  //获取排序select 下来菜单 $id = -999 , $pid = -999


		}


		//设置表单 添加
		function setFormAdd(){
			console.log('setFormAdd:');

			var $form = $('#form1');

            var node = zTree.getSelectedNodes();
            if( node.length == 0 ){ alert('请选选择部门节点~~~') ; return ; }
            node = node[0];

			var pid = node.id ;
			var pname = node.name;

			if( isNaN(pid) ){ alert('请选选择部门节点，在点添加~~~') ; return ; }



			
			$form.find('#action_title ').text('添加') ; 

			$form.find('[name=name]').val('') ;  
			$form.find('[name=id]').val('') ;  

			$form.find('[name=pname]').val(pname) ;  
			$form.find('[name=pid]').val(pid) ;  

			$form.find('[name=info]').val('') ; 

			setSortSelect( null , pid ) ;  //获取排序select 下来菜单 $id = -999 , $pid = -999

			



		}


		//获取排序select 下来菜单
		function setSortSelect( $id = -999 , $pid = -999 ){
			console.log('setSortSelect:' , $id , $pid  );

			var $select =  $('#form1 [name=sort]'); // 下拉框
			var id =  $id ;
			var pid = $pid ;
			var nodes = []; 
			var select_id = 0 ;

            $select.empty();
			

			for(var i = 0 , len = zNodes.length ; i < len  ;  i++  ){
				if ( zNodes[i].pid == pid  ) {
					nodes.push(zNodes[i]);
				};
			}

			for(var i = 0 , len = nodes.length ; i < len  ;  i++  ){
				if ( nodes[i].id != id  ) {
					$select.append('<option value="' + nodes[i].id + '" >位于 [ '+ nodes[i].name +' ] 之前</option>');
				}else{
					select_id = nodes[i+1] ? nodes[i+1].id : 0 ;
				};
			}

            $select.append('<option value="0" >同级部门最后位置</option>');

			$select.val(select_id) ;

		}

		// function getNodeByParam( key = null , value = null ){
		// 	console.log('getNodeByParam:' , key , value);

		// 	for(var i = 0 , len = zNodes.length ; i < len  ;  i++  ){
		// 		if ( zNodes[i][key] == value  ) {
		// 			//nodes.push(zNodes[i]);
		// 			return zNodes[i];
		// 		};
		// 	}

		// }



		
// var code;

		
// function showCode(str) {
// 	if (!code) code = $("#code");
// 	code.empty();
// 	code.append("<li>"+str+"</li>");
// }
function zTree_reload(){
	var url_notes = "{:url('zNodes')}";//获取url 


	// jBox.tip('loading...' , 'loading');
    $.ajax({
        type:'post',
        url:url_notes,
        data: {},
        dataType:'json',
        success:function(d){

        		jBox.closeTip();
        		zNodes = d;
        		zTree_init();


        		
var nodes = zTree.getNodes();
if (nodes.length>0) {
	zTree.selectNode(nodes[0],true);
	setting.callback.beforeClick('' , nodes[0] );
}
        },
        error:function(a,b,c){
            jBox.tip('ajax error：' + b );


                    		jBox.closeTip();
        		zTree_init();
        }
    });

}

function zTree_init(){
		
	zTree = $.fn.zTree.init(t, setting, zNodes);
	
	var cookie = $.cookie("z_tree");  
    if(cookie){  
        z_tree = JSON.parse(cookie);  
        for(var i=0; i< z_tree.length; i++){  
	        var node = zTree.getNodeByParam('id', z_tree[i])  
	        zTree.expandNode(node, true)  
        }  
    }  
}


//展开折叠切换
var flag_expand = false;
function expandAll(obj){
	if(! $(obj).length ) return false ;
	var z_tree = [];

	if( flag_expand ){
		$(obj).text(' 展开');
		//z_tree = [];

	}else{
		$(obj).text(' 折叠');
		for(var i = 0 , len = zNodes.length ; i < len  ;  i++  ){
			z_tree.push( zNodes[i].id );
		}
	}

	$.cookie("z_tree", JSON.stringify(z_tree));
	zTree.expandAll(flag_expand = !flag_expand);
	// var node = zTree.getNodeByParam("id", 5);
	// zTree.selectNode(node, true, true);
	// zTree.checkNode(node, true, true);

}
function btn_zTree_reload(){
	zTree_reload();
	setFormReset();
}

//删除按钮
function btn_delNode(){

    var url_del = '{:url('delete')}';

    var node = zTree.getSelectedNodes();
        if(!node || !node.length ){
            jBox.tip('请选择要删除的部门~~~');return;
        }
        node = node[0] ;

    var doDel = function(){
        // jBox.tip('处理中...666' , 'loading');  

        $.ajax({
            type:'post',
            url:url_del,
            data: {id : node.id},
            dataType:'json',
            success:function(d){
            	if(d.ret == 0 ){
            		jBox.tip( '删除成功！' + d.msg + '!!', 'success' );
            		setTimeout(function(){
						// window.location.replace(location.href);
						// window.location.href=location.href
						//location.reload();
						zTree_reload();
            		},3000);
            	}else{
            		top.jBox.tip( d.msg , 'error' );
            	}
            },
            error:function(a,b,c){
                jBox.tip('ajax error：' + b );
            }
        });
    }
    

    var submit = function (v, h, f) {
        if (v == 'ok'){
            doDel();
        }else if (v == 'cancel'){
            jBox.tip('取消...', 'info');
        }
        return true; //close
    };

    $.jBox.confirm("确定 删除吗？", "提示", submit);


}



$(document).ready(function(){
	//zTree_init();
	zTree_reload();
	setFormReset()

	//top.$.jBox.alert('content', 'title' );
    //top.$.jBox.alert('Hello jBox');;
    //h.tip('成功','loading'); // 'info'、'success'、'warning'、'error'、'loading'，
    //
    //$.jBox.messager('Hello <br/> jBox', );
    //


	//$.jBox('<div style="width:340px; height:300px; background:#f60;" >width:340px; height:300px; background:#f60;</div>');

                
	$('#form1').validate({
		onkeyup:false, //在 keyup 时验证。
        onclick:true, // 在点击复选框和单选按钮时验证。
        onfocusout:false, //失去焦点时验证（不包括复选框/单选按钮）。
        onsubmit:true ,   // 提交时验证。设置为 false 就用其他方法去验证。
		focusCleanup:true,focusInvalid:false,
		//success:"valid", //验证成功 添加样式
		//
		rules: {
	      	pname:{
	        	required:function(a,b,c){
	        		return !$('[name=pid]').val();
	        	},
		    },
      	},
		submitHandler:function(form){
			
            jBox.tip('loading...' , 'loading') ; 
			
			//http://www.h-ui.net/lib/jQuery.form.js.shtml
			var a = $(form).ajaxSubmit({
				success:function(d){
                    console.log(d);
                    console.log( d.ret != 0  );
					if( d.ret == 0  ){
                        
                        top.jBox.tip( '保存成功' + d.msg + '!!', 'success' );
	            		setTimeout(function(){
							// window.location.replace(location.href);
							// window.location.href=location.href
							// location.reload();
							zTree_reload();
							setFormReset()
							
	            		},2000);
                    }else{
                        jBox.tip( d.msg ,'error');
                    }

				},
                error:function(){
                    alert('ajax error:');
                    jBox.closeTip();
                }

			});

			
			//location.replace(location.href);
			
			//parent.$('.btn-refresh').click();
			//var index = parent.layer.getFrameIndex(window.name);
			//parent.layer.close(index);
		},
		showErrors:function(errorMap,errorList) {
			this.defaultShowErrors(); //默认验证 
            // 判断 错误数量  
			if( this.numberOfInvalids() ){
				h.tip( '有' + this.numberOfInvalids() + '个错误，请检查！' ,'error');
			}
    	}
	});



	
	
	// $( '[deptselect]' ).deptselect({id:100});


});






</script>

<style>

	
</style>



{/block}{//---------------------------------------------------------------------------}